# -*- coding: utf-8 -*-
# @Time : 2021/9/1 18:20
# @Author : 唐宁
# @Site : 
# @File : ExceptionHandler.py
# @Software: PyCharm

# 统一异常封装

from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from fastapi.logger import logger
from starlette.responses import JSONResponse

from exception.ErrorCodeEnum import ErrorCodeEnum
from exception.ErrorCodeException import ErrorCodeException


class ExceptionHandler:

    @staticmethod
    def register(app: FastAPI) -> None:
        @app.exception_handler(RequestValidationError)
        def validation_exception_handler(request, exc: RequestValidationError):
            """
            参数验证失败情况
            :param request: 这个参数不能省
            :param exc: 参数验证错误
            :return: JSONResponse
            """
            logger.error(exc)
            return JSONResponse(
                content={"msg": ErrorCodeEnum.INVALID_PARAMS.msg, "code": ErrorCodeEnum.INVALID_PARAMS.code},
                status_code=200)

        @app.exception_handler(ErrorCodeException)
        def error_code_exception_handler(request, exc: ErrorCodeException):
            """
            自定义异常处理
            :param exc: 自定义异常信息
            :param request:  请求
            :return:  JSONResponse
            """
            logger.error(exc)
            return JSONResponse(content={"msg": exc.msg, "code": exc.ex.code},
                                status_code=200)

        @app.exception_handler(Exception)
        def global_exception(request, exc: Exception):
            """
            全局异常捕获，任意异常
            :param request: 请求
            :param exc: 异常信息
            :return: JSONResponse
            """
            logger.error(exc)
            return JSONResponse(content={"msg": ErrorCodeEnum.ERROR.msg, "code": ErrorCodeEnum.ERROR.code},
                                status_code=200)
